package com.shadowtorcher.soulknife.tableManager;
/*
 * Copyright (C)  li, Shadow Torcher project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.shadowtorcher.soulknife.parser.SoulKnifeConfig;
import com.shadowtorcher.soulknife.parser.TypeConverter;
import com.shadowtorcher.soulknife.util.Logger;
import com.shadowtorcher.soulknife.util.Metadata;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeMap;


public class Manager {
    public static HashSet<String> Inited = new HashSet<>();

    public static void init(Class object) throws SQLException {
        String name = object.getSimpleName();
        if (Inited.contains(name) || name.equals(Metadata.class.getSimpleName())) {
            return;
        }
        if (SQLManager.haveTable(name)) {
            Updater.doUpdate(object, SoulKnifeConfig.SchemasVersion);
            Inited.add(name);
            return;
        }
        createTable(object);
    }

    private static boolean isMetaData(Class object) {
        return object.getSimpleName().equals(Metadata.class.getSimpleName());
    }

    public static void createTable(Class object) throws SQLException {
        if (SQLManager.haveTable(object.getSimpleName()))
            return;
        Map<String, String> valNameToSQLTypeMap = new TreeMap<>();
        Field[] field = object.getDeclaredFields();
        for (Field afield : field) {
            String val = afield.getName();
            String type = afield.getGenericType().toString();
            Logger.logI("get val name " + val + " type " + type);
            valNameToSQLTypeMap.put(val, TypeConverter.javaToSQL(type));
        }
        valNameToSQLTypeMap.put("PRIMARY_KEY", TypeConverter.javaToSQL("long"));
        Creator.createTable(object.getSimpleName(), valNameToSQLTypeMap);
        Inited.add(object.getSimpleName());
    }
}
